<?php

namespace App\Admin\Controllers\OwnerItem;

use App\Admin\Repositories\OwnerItem;
use App\Models\Building;
use App\Models\House;
use Dcat\Admin\Grid;
use Dcat\Admin\IFrameGrid;
use Dcat\Admin\Layout\Content;

// 账单列表

class BillController extends CommonOwnerItemController
{
    protected $title = "收入流水";

    public function index(Content $content)
    {
        if (request(IFrameGrid::QUERY_NAME)) {
            return $content->perfectScrollbar()->body($this->iFrameGrid());
        }

        return $content
            ->title($this->title())
            ->description($this->description()['index'] ?? trans('admin.list'))
            ->body($this->grid());
    }

    protected function grid()
    {
        return Grid::make(new OwnerItem(['owner', 'owner.ownerable', 'owner.user']), function (Grid $grid) {
            $grid->model()->where('pay_at', '!=', null)->orderBy('id', 'desc');
            $grid->id->sortable();
            $grid->column('owner.ownerable', '关联的房间（楼栋或房产）')->display(function ($value) {
                if (isset($value['building_id'])) {  // 房间详细名称显示
                    $building = Building::query()->with('house')->find($value['building_id']);
                    return $building->house->name . " - " . $building->name. " - " . $value['name'];
                }
                if (isset($value['house_id'])) {
                    $house = House::query()->find($value['house_id']);
                    return $house->name . " - ". $value['name'];
                }
                return $value['name'];
            });
            $grid->column('owner.user', '付款业主')->display(function ($value) {
                return $value['name'];
            });
            $grid->count('第几期')->display(function ($value) {
                return "第{$value}期租金";
            });
            $grid->total_amount('入账金额')->display(function ($value) {
                return $value ? $value . "元": "error";
            });
            $this->customGrid($grid);
            $grid->pay_at('支付时间')->sortable();
            $grid->disableCreateButton();
            $grid->disableEditButton();
            $grid->disableDeleteButton();

            $grid->filter(function (Grid\Filter $filter) {
                // 更改为 panel 布局
                $filter->panel();
                // 注意切换为panel布局方式时需要重新调整表单字段的宽度
                $filter->equal('id', '流水编号')->width(3);
                $filter->between('pay_at', '支付时间')->width(3)->datetime();
                $filter->equal('count', '第几期交租')->width(3);
                $filter->between('rent', '租金范围')->width(3);
                $filter->between('total_amount', '入账金额范围')->width(3);
            });
        });
    }

    protected function map(): array
    {

    }

    protected function customGrid(Grid $grid)
    {
        // TODO: Implement customGrid() method.
    }

    protected function customDetail($show)
    {
        // TODO: Implement customDetail() method.
    }
}
